#!/bin/bash

# 确保group.txt文件存在
if [ ! -f "group.txt" ]; then
    echo "错误: group.txt文件不存在，请先运行 get_repos.py 脚本"
    exit 1
fi

# 统计计数器
total_repos=0
total_success=0
total_failed=0
total_groups=0

# 读取group.txt中的每一行（每个代码组）
while IFS= read -r group_name; do
    # 跳过空行
    if [ -z "$group_name" ]; then
        continue
    fi
    
    # 处理组名，使其成为有效的文件名
    group_file="${group_name// /_}.txt"
    group_file="${group_file//\//_}"
    
    # 检查对应的txt文件是否存在
    if [ ! -f "$group_file" ]; then
        echo "警告: $group_file 文件不存在，跳过处理组 '$group_name'"
        continue
    fi
    
    total_groups=$((total_groups+1))
    
    # 创建代码组目录（如果不存在）
    group_dir="${group_name// /_}"
    group_dir="${group_dir//\//_}"
    
    if [ ! -d "$group_dir" ]; then
        mkdir -p "$group_dir"
        echo "已创建目录: $group_dir"
    else
        echo "目录已存在: $group_dir"
    fi
    
    # 进入组目录
    cd "$group_dir" || { echo "无法进入目录 $group_dir，跳过"; continue; }
    
    # 计数器
    group_total=$(wc -l < "../$group_file")
    current=0
    success=0
    failed=0
    
    echo "====================================="
    echo "开始处理代码组: $group_name (共 $group_total 个仓库)"
    echo "====================================="
    
    # 读取每一行并克隆仓库
    while IFS= read -r repo_url; do
        # 跳过空行
        if [ -z "$repo_url" ]; then
            continue
        fi
        
        current=$((current+1))
        total_repos=$((total_repos+1))
        
        # 从URL中提取仓库名称
        repo_name=$(basename "$repo_url" .git)
        
        echo "[$current/$group_total] 正在克隆: $repo_name"
        
        # 如果目录已存在则跳过克隆
        if [ -d "$repo_name" ]; then
            echo "✓ 目录已存在，跳过克隆: $repo_name"
            success=$((success+1))
            total_success=$((total_success+1))
        else
            # 克隆仓库
            if git clone "$repo_url"; then
                echo "✓ 成功克隆: $repo_name"
                success=$((success+1))
                total_success=$((total_success+1))
            else
                echo "✗ 克隆失败: $repo_name"
                failed=$((failed+1))
                total_failed=$((total_failed+1))
            fi
        fi
        
        echo "-----------------------------------"
    done < "../$group_file"
    
    echo "代码组 '$group_name' 处理完成: 共 $group_total 个仓库，成功 $success 个，失败 $failed 个"
    echo ""
    
    # 返回上级目录
    cd .. || { echo "无法返回上级目录，脚本退出"; exit 1; }
    
done < group.txt

echo "======================================================"
echo "所有代码组处理完成: 共 $total_groups 个代码组，$total_repos 个仓库，成功 $total_success 个，失败 $total_failed 个"
echo "======================================================" 